package com.czk.servletSpi.myConfig;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.Set;

/**
 * WebConfig作为ServletContainerInitializer的实现类，它的作用是扫描找到WebParameter的实现类，并调用其方法
 *
 * @Author:ChenZhangKun
 * @Date: 2021/4/27 23:02
 */
@HandlesTypes({WebParameter.class})
public class WebConfig implements ServletContainerInitializer {

    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        Iterator iterator;
        if (set != null) {
            // 拿到迭代器
            iterator = set.iterator();
            // 遍历
            while (iterator.hasNext()) {
                // 拿到字节码
                Class<?> clazz = (Class<?>) iterator.next();
                // 父类.class.isAssignableFrom(子类.class)
                // 子类实例 instanceof 父类类型
                if (!clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()) && WebParameter.class.isAssignableFrom(clazz)) {
                    // 执行方法
                    try {
                        ((WebParameter) clazz.newInstance()).onStartUp(servletContext);
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
